package com.my.lab.receiver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;

import com.my.lab.PhoneUtils;

public class ComeingCallReceiver extends BroadcastReceiver {
    static String TAG = "ComeingCallReceiver";
    static final String ACTION = "android.intent.action.NEW_OUTGOING_CALL";
    Intent intent = null;
    

    @Override
    public void onReceive(Context context, Intent intent) {
	Log.d(TAG, "onReceive...");
	if (intent.getAction().equals(ACTION)) {
	    Log.d(TAG, "onReceivd:outgoing_call");
	} else {
	    TelephonyManager tm = (TelephonyManager) context
		    .getSystemService(Service.TELEPHONY_SERVICE);
	    switch (tm.getCallState()) {
	    case TelephonyManager.CALL_STATE_RINGING:
		Log.d(TAG, "call ringing");
//		context.startService(new Intent(context, WondieService.class));
		try {
		    String num = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
		    if(num.equals("13763062346"))
			PhoneUtils.getItelephony(tm).endCall();
		    // PhoneUtils.getItelephony(tm).silenceRinger();
		    // PhoneUtils.getItelephony(tm).answerRingingCall();
		} catch (RuntimeException e) {
		    // TODO Auto-generated catch block
		    intent = new Intent("android.intent.action.MEDIA_BUTTON");
		    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN,
			    KeyEvent.KEYCODE_HEADSETHOOK);
		    intent.putExtra("android.intent.extra.KEY_EVENT", keyEvent);
		    context.sendOrderedBroadcast(intent,
			    "android.permission.CALL_PRIVILEGED");
		    intent = new Intent("android.intent.action.MEDIA_BUTTON");
		    keyEvent = new KeyEvent(KeyEvent.ACTION_UP,
			    KeyEvent.KEYCODE_HEADSETHOOK);
		    intent.putExtra("android.intent.extra.KEY_EVENT", keyEvent);
		    context.sendOrderedBroadcast(intent,
			    "android.permission.CALL_PRIVILEGED");
		    System.out.println(e.toString());
		} catch (RemoteException e) {
		    // TODO Auto-generated catch block
		    System.out.println(e.toString());
		}

		break;
	    case TelephonyManager.CALL_STATE_IDLE:
		Log.d(TAG, "call idle");
	    case TelephonyManager.CALL_STATE_OFFHOOK:
		Log.d(TAG, "call offhook");
		break;
	    }
	}

    }

}
